<!-- 视图多边形 -->

<template>
  <div v-show="!hide && area.length" :class="areaClass">
    <div class="Secure-MapView-area-bg" :style="bgStyle" @click.stop="toEdit" />
    <div class="Secure-MapView-area-dot" v-for="(item, i) in area" :key="i" :style="getDotStyle(item)" />
    <div class="Secure-MapView-area-text" :style="textStyle">{{ obj.name }}</div>
  </div>
</template>

<script>
// ============================== 导入依赖 ============================== //

import CORE from '@/CORE'
import props from './props'

// ============================== 导出组件 ============================== //

export default {
  /**
   * 名称定义 (实际使用名称)
   */
  name: 'ViewArea',

  /**
   * 混入列表 (配置选项合并)
   */
  mixins: [CORE.mixWeb('map', 'map_')],

  /**
   * 属性注册 (抽取以便查阅)
   */
  props,

  /**
   * 计算属性 (慎用箭头函数)
   */
  computed: {
    /**
     * 父组件视图
     */
    parentView() {
      return CORE.componentParent(this, 'MapView') || {}
    },

    /**
     * 多边形区域
     */
    area() {
      const { location } = this.obj
      if (!location || location === 'none') return []

      return location.split(',').map((str) => str.split(' '))
    },

    /**
     * 区域样式类
     */
    areaClass() {
      const { map_one, obj } = this
      const name = 'Secure-MapView-area'
      const marking = map_one.id ? ` ${name}-marking` : ''
      const replaced = map_one.id === obj.id ? ` ${name}-replaced` : ''
      return `${name}${marking}${replaced}`
    },

    /**
     * 背景样式对象
     */
    bgStyle() {
      const { area, $parent: { map_readyInfo, readyImg } } = this
      if (!area.length) return { display: 'none' }

      const opacity = map_readyInfo && readyImg ? 1 : 0
      const str = area.map(([x, y]) => `${x}% ${y}%`).join()
      return { opacity, clipPath: `polygon(${str})` }
    },

    /**
     * 文字样式对象
     */
    textStyle() {
      const { hide, area, $parent: { readyImg }, parentView: { scale = 1 } } = this
      if (!area.length) return { display: 'none' }

      const left = CORE.div(area.reduce((total, [x]) => total + +x, 0), area.length)
      const top = CORE.div(area.reduce((total, [, y]) => total + +y, 0), area.length)
      const opacity = readyImg ? 1 : 0
      const display = hide || !left || !top ? 'none' : null
      const transform = `translate(-50%, -50%) scale(${1 / scale})`
      return { display, opacity, left: `${left}%`, top: `${top}%`, transform }
    },
  },

  /**
   * 本地方法 (轻量重要在前)
   */
  methods: {
    /**
     * 点击修改
     */
    toEdit() {
      this.map_openEdit(this.obj)
    },

    /**
     * 获取圆点样式
     */
    getDotStyle([left, top]) {
      const { $parent: { map_readyInfo, readyImg }, parentView: { scale = 1 } } = this
      const opacity = map_readyInfo && readyImg ? 1 : 0
      const transform = `translate(-50%, -50%) scale(${1 / scale})`
      return { opacity, left: `${left}%`, top: `${top}%`, transform }
    },
  },
}
</script>
